package com.android.studyspot;

import java.net.MalformedURLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.TableOperationCallback;
import com.microsoft.windowsazure.mobileservices.TableQueryCallback;

import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class AddStudySpotActivity extends SherlockFragmentActivity implements OnDateSetListener, OnTimeSetListener{
	private Bundle hashmap;
	private ArrayList<String> courseList;
	private MobileServiceTable<StudySpotTable> m_studySpotTable;
	private MobileServiceTable<courses> m_coursesTable;
	private MobileServiceTable<users_studyspot> m_usersStudySpotTable;
	private String details;
	private Timestamp start, end;
	private Button setDateButton;
	private Button setStartTimeButton;
	private Button setEndTimeButton;
	private boolean startTimeClicked;
	private Typeface tf;
	private int month, day, year, startHourOfDay, startMinute, endHourOfDay, endMinute;
	
	private static final int ACTIVE_STUDY_SPOT = 1;
	private static final  int CAL_POLY_ID = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		hashmap = this.getIntent().getExtras();
		courseList = new ArrayList<String>();
		tf = Typeface.createFromAsset(getAssets(),"fonts/futuraCondensed.ttf");
		
		System.gc();
		initLayout();
	
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.add_study_spot_menu, menu);
        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.save_new_studyspot:
				createStudySpot();
				return true;
			default:
				return true;
		}
	}
	
	private void initLayout() {
		Spinner courseSpinner;
		TextView courseLabel, dateTimeLabel, locationLabel;
		
		setContentView(R.layout.layout_add_studyspot);
		
		this.setDateButton = (Button)this.findViewById(R.id.ss_setDateButton);
		this.setStartTimeButton = (Button)this.findViewById(R.id.ss_setStartTimeButton);
		this.setEndTimeButton = (Button)this.findViewById(R.id.ss_setEndTimeButton);
		courseLabel = (TextView)this.findViewById(R.id.ss_course_label);
		courseLabel.setTypeface(tf);
		dateTimeLabel = (TextView)this.findViewById(R.id.ss_date_time_label);
		dateTimeLabel.setTypeface(tf);
		locationLabel = (TextView)this.findViewById(R.id.ss_location_label);
		locationLabel.setTypeface(tf);
		
		this.setDateButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				DialogFragment newFragment = new DatePickerFragment();
			    newFragment.show(getSupportFragmentManager(), "datePicker");
			    
			}
			
		});
		
		this.setStartTimeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startTimeClicked = true;
				DialogFragment newFragment = new TimePickerFragment();
			    newFragment.show(getSupportFragmentManager(), "timePicker");
			}
			
		});
		
		this.setEndTimeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startTimeClicked = false;
				DialogFragment newFragment = new TimePickerFragment();
			    newFragment.show(getSupportFragmentManager(), "timePicker");
			}
			
		});
		
		courseSpinner = (Spinner)this.findViewById(R.id.ss_course_spinner);
		
		for (int i=0; i<hashmap.size()-1; i++) {
			courseList.add(hashmap.getString("course-"+ i));
		}
		
		// Course spinner is filled with values
		ArrayAdapter<String> courseAdapter = new ArrayAdapter<String>(AddStudySpotActivity.this, R.layout.sherlock_spinner_item, courseList);
		courseAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		courseSpinner.setAdapter(courseAdapter);
	}
	
	public void onDateSet(DatePicker view, int year, int month, int day) {
    	TextView tv = (TextView) this.findViewById(R.id.ss_dateTV);
    	tv.setTypeface(tf);
    	
    	tv.setText((month+1) + "/" + day + "/" + year);
    	
    	this.month = month+1;
    	this.day = day;
    	this.year = year;
    }
	
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		TextView tv;
		
		if (startTimeClicked) {
			this.startHourOfDay = hourOfDay;
			this.startMinute = minute;
			
			tv = (TextView) this.findViewById(R.id.ss_startTimeTV);
			setTimeTV(tv, hourOfDay, minute);
		}
		else {
			this.endHourOfDay = hourOfDay;
			this.endMinute = minute;
			
			tv = (TextView) this.findViewById(R.id.ss_endTimeTV);
			setTimeTV(tv, hourOfDay, minute);
		}
    }
	
	private void setTimeTV(TextView tv, int hourOfDay, int minute) {
		tv.setTypeface(tf);
		
		if (hourOfDay == 0) {
			if (minute > 10) {
				tv.setText((hourOfDay+12) + ":" + minute + " AM");
			}
			else {
				tv.setText((hourOfDay+12) + ":0" + minute + " AM");
			}
		}
		else if (hourOfDay < 12) {
			if (minute > 10) {
				tv.setText(hourOfDay + ":" + minute + " AM");
			}
			else {
				tv.setText(hourOfDay + ":0" + minute + " AM");
			}
		}
		else if (hourOfDay == 12) {
			if (minute > 10) {
				tv.setText(hourOfDay + ":" + minute + " PM");
			}
			else {
				tv.setText(hourOfDay + ":0" + minute + " PM");
			}
		}
		else {
			if (minute > 10) {
				tv.setText((hourOfDay-12) + ":" + minute + " PM");
			}
			else {
				tv.setText((hourOfDay-12) + ":0" + minute + " PM");
			}
		}
	}
	
	private void createStudySpot() {
//		int month, day;
//		String year; 
		String startDateTime, endDateTime, startTime, endTime;
		SimpleDateFormat dateFormat;
		Date parsedStartDate, parsedEndDate;
		Spinner courseSpinner;
		
		try {
			MobileServiceClient mClient = new MobileServiceClient(
				      "https://studyspot.azure-mobile.net/",
				      "UeeXTmfsscRIhhVuCyRqDRwfThBDPa90",
				      this
			);
			
			this.m_studySpotTable = mClient.getTable("studyspot", StudySpotTable.class);
			this.m_coursesTable = mClient.getTable(courses.class);
			this.m_usersStudySpotTable = mClient.getTable(users_studyspot.class);
			
			details = ((EditText)this.findViewById(R.id.ss_details_edit_text)).getText().toString();
//			month = ((DatePicker)this.findViewById(R.id.ss_date_picker)).getMonth() + 1;
//			day = ((DatePicker)this.findViewById(R.id.ss_date_picker)).getDayOfMonth();
//			year = "2013";
			
//			if (((TimePicker)this.findViewById(R.id.start_time_picker)).getCurrentMinute() < 10) {
//				startTime = ((TimePicker)this.findViewById(R.id.start_time_picker)).getCurrentHour() + 
//						":0" + ((TimePicker)this.findViewById(R.id.start_time_picker)).getCurrentMinute() + ":00";
//			}
//			else {
//				startTime = ((TimePicker)this.findViewById(R.id.start_time_picker)).getCurrentHour() + 
//						":" + ((TimePicker)this.findViewById(R.id.start_time_picker)).getCurrentMinute() + ":00";
//			}
//			
//			if (((TimePicker)this.findViewById(R.id.end_time_picker)).getCurrentMinute() < 10) {
//				endTime = ((TimePicker)this.findViewById(R.id.end_time_picker)).getCurrentHour() + 
//						":0" + ((TimePicker)this.findViewById(R.id.end_time_picker)).getCurrentMinute() + ":00";
//			}
//			else {
//				endTime = ((TimePicker)this.findViewById(R.id.end_time_picker)).getCurrentHour() + 
//						":" + ((TimePicker)this.findViewById(R.id.end_time_picker)).getCurrentMinute() + ":00";
//			}
			
			if (this.startMinute < 10) {
				startTime = this.startHourOfDay + ":0" + this.startMinute + ":00";
			}
			else {
				startTime = this.startHourOfDay + ":" + this.startMinute + ":00";
			}
			
			if (this.endMinute < 10) {
				endTime = this.endHourOfDay + ":0" + this.endMinute + ":00";
			}
			else {
				endTime = this.endHourOfDay + ":" + this.endMinute + ":00";
			}
			
			startDateTime = year + "-" + month + "-" + day + " " + startTime;
			
			endDateTime = year + "-" + month + "-" + day + " " + endTime; 
			
			try {
				dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
				
				parsedStartDate = dateFormat.parse(startDateTime);
				parsedEndDate = dateFormat.parse(endDateTime);
				
				start = new Timestamp(parsedStartDate.getTime());
				end = new Timestamp(parsedEndDate.getTime());
				
				courseSpinner = ((Spinner)this.findViewById(R.id.ss_course_spinner));
				
				this.m_coursesTable.where().field("course").eq(courseSpinner.getSelectedItem().toString())
				.execute(new TableQueryCallback<courses>() {

					@Override
					public void onCompleted(List<courses> result, int count,
							Exception exception, ServiceFilterResponse response) {
						if (exception == null) {
							StudySpotTable ss = new StudySpotTable(AddStudySpotActivity.CAL_POLY_ID, result.get(0).id, start, end, 
									hashmap.getInt("userId"), AddStudySpotActivity.ACTIVE_STUDY_SPOT, details);
							
							m_studySpotTable.insert(ss, new TableOperationCallback<StudySpotTable>() {

								@Override
								public void onCompleted(StudySpotTable entity, Exception exception,
										ServiceFilterResponse response) {
									if (exception == null) {
										users_studyspot us = new users_studyspot();
										us.us_ssid = entity.getId();
										us.us_status = entity.getStatus();
										us.us_userid = hashmap.getInt("userId");
										
										m_usersStudySpotTable.insert(us, new TableOperationCallback<users_studyspot>() {

											@Override
											public void onCompleted(
													users_studyspot entity,
													Exception exception,
													ServiceFilterResponse response) {
												if (exception == null) {
													Intent studySpotActivityStart = new Intent(AddStudySpotActivity.this, StudySpotsActivity.class);
													studySpotActivityStart.putExtra("userId", hashmap.getInt("userId"));
													
													
													for (int i=0; i<hashmap.size()-1; i++) {
														studySpotActivityStart.putExtra("course-" + i, hashmap.getString("course-" + i));
													}
													
													startActivity(studySpotActivityStart);
												}
												else {
													Log.e("StudySpot", exception.getMessage());
												}
											}
										});
									}
									else {
										Toast toast = Toast.makeText(AddStudySpotActivity.this, "Add not successful!", Toast.LENGTH_LONG);
										toast.show();
									}
								}
							});
						}
						else {
							Log.d("StudySpot", exception.getMessage());
						}
					}
				});
			}
			catch (ParseException e) {
				//Do nothing for now
			}
		}
		catch (MalformedURLException e) {
			Log.d("Azure", e.getMessage());
			e.printStackTrace();
		}
	}
}
